﻿namespace JxcLite.Services;

class FinanceService(Context context) : ServiceBase(context), IFinanceService
{
    public Task<PagingResult<JxAccountHead>> QueryAccountsAsync(PagingCriteria criteria)
    {
        return Database.QueryPageAsync<JxAccountHead>(criteria);
    }

    public async Task<JxAccountHead> GetDefaultAccountAsync(string type)
    {
        return new JxAccountHead
        {
            Type = type,
            AccountNo = await Database.GetMaxAccountNoAsync(type),
            Status = FlowStatus.Save,
            AccountDate = DateTime.Now
        };
    }

    public async Task<Result> DeleteAccountsAsync(List<JxAccountHead> models)
    {
        if (models == null || models.Count == 0)
            return Result.Error(Language.SelectOneAtLeast);

        var oldFiles = new List<string>();
        var result = await Database.TransactionAsync(Language.Delete, async db =>
        {
            foreach (var item in models)
            {
                await db.DeleteFilesAsync(item.Id, oldFiles);
                await db.DeleteAsync<JxAccountList>(d => d.HeadId == item.Id);
                await db.DeleteAsync(item);
            }
        });
        if (result.IsValid)
            AttachFile.DeleteFiles(oldFiles);
        return result;
    }

    public async Task<Result> SaveAccountAsync(UploadInfo<JxAccountHead> info)
    {
        var model = info.Model;
        var vr = model.Validate(Context);
        if (!vr.IsValid)
            return vr;

        var user = CurrentUser;
        var bizType = "AccountFiles";
        var bizFiles = info.Files.GetAttachFiles(user, nameof(JxAccountHead.Files), bizType);
        return await Database.TransactionAsync(Language.Save, async db =>
        {
            if (model.IsNew)
                model.AccountNo = await db.GetMaxAccountNoAsync(model.Type);
            await db.AddFilesAsync(bizFiles, model.Id, bizType);
            model.Files = $"{model.Id}_{bizType}";
            await db.SaveAsync(model);
        }, model);
    }
}